<?php
if (isset($_POST['army'], $_POST['coordinates'], $_POST['order']) && is_array($_POST['army']))
{
	$page['vars']['move'] = array('coordinates' => null);
	$vars = &$page['vars']['move'];

	$planet = U1_DAO_Planet::selectByCoordinates($_POST['coordinates'], $vars['coordinates']);
	$units = new U1_Units($_POST['army'], false);
	$resources = null;
	if (isset($_POST['resources']) && is_array($_POST['resources']))
		$resources = new U1_Removable_Resource($_POST['resources']);

	$exception = null;
	try{
		if (!$planet)
			throw new InvalidArgumentException('La planète n\'existe pas');

		$move = U1_Move::getMoving($_POST['order'], $planet->getId(), $resources);
		$order = $move->getOrderName();

		$moveArmy = new U1_Move_Units($planets->getCurrentId(), $units, $move);

		if ($id = $moveArmy->send())
			$vars['id'] = $id;
		else
			throw new U1_Move_Units_Exception('Impossible d\'envoyer l\'armé');
	}
	catch (Exception $e)
	{
		$vars['error'] = $e->getMessage();

		//U1_Move::getMoving
		if ($e instanceof InvalidArgumentException)
			$order = htmlspecialchars((string)$_POST['order'], ENT_QUOTES, 'UTF-8');
		else if (!($e instanceof U1_Move_Units_Exception))
			$exception = $e;
	}

	$vars['order'] = $order;
	$vars['units'] = $units->toArray();
	$vars['idPlanet'] = $planets->getCurrentId();
	$vars['resources'] = $resources ? $resources->getQuantities() : null;

	if ($exception)
		throw $exception;
}